extends Node
class_name RecipeBook

@export var all_recipes : Array[ItemRecipe]
var _sig2recipe : Dictionary = {}
var recipe_csv: RecipeCsv = RecipeCsv.new()
var csv_path = "res://data/item_pool/recipe_csv/data/recipe_csv.txt"

func _init() -> void:
	var recipes_csv :Array = recipe_csv.load(csv_path)
	for recipe in recipes_csv:
		var item_recipe = ItemRecipe.new(recipe["id1"],recipe["id2"],recipe["target_id"])
		all_recipes.append(item_recipe)
		
	# 构建哈希表
	for r in all_recipes:
		var sig := r.get_signature()
		if _sig2recipe.has(sig):
			push_error("Duplicate recipe signature: %s" % sig)
		_sig2recipe[sig] = r

# 参数 either: Dictionary(PandoraEntity:int) 或者直接 Array[PandoraEntity] 不含数量
func find_recipe(input) -> ItemRecipe:
	var sig:String
	if input is Dictionary:
		sig = ItemRecipe.make_signature(input)
	else:
		# 传进来的是 [wood, wood, iron]
		var d := {}
		for i in input:
			d[i] = d.get(i, 0) + 1
		sig = ItemRecipe.make_signature(d)
	return _sig2recipe.get(sig, null)

## 获取可一起合成的装备的名字
func get_sub_recipe(id) -> Array:
	var result = []
	# 遍历所有配方，查找包含该id作为材料的配方
	for recipe in all_recipes:
		var sub_result = []
		if recipe.item1_id == id:
			var target_name = ItemManager.get_item_name(recipe.item2_id)
			if target_name and not result.has(target_name):
				sub_result.append(target_name)
				sub_result.append(ItemManager.get_item_name(recipe.target_id))
				result.append(sub_result)
		if recipe.item2_id == id:
			var target_name = ItemManager.get_item_name(recipe.item1_id)
			if target_name and not result.has(target_name):
				sub_result.append(target_name)
				sub_result.append(ItemManager.get_item_name(recipe.target_id))
				result.append(sub_result)
	return result

